package com.icodingedu.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
//GatewayFilter--->GlobalFilter
public class TimerFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //给接口调用计时并能够输出漂亮的log
        StopWatch timer = new StopWatch();
        timer.start(exchange.getRequest().getURI().getRawPath());//开始计时

        return chain.filter(exchange).then(
            //这里就是执行完过滤进行调用的地方
            Mono.fromRunnable(() ->{
                timer.stop();
                log.info(timer.prettyPrint());
            })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
